const ACCESS_KEY = "W7gcftWVGrMQqaEFkrG9m2uN";
const ACCESS_SECRET = "fDhpQOWCvToWrwea6FTBunlQaUiKIDbg";
// 获取token
export function getBaiduVoiceToken() {
  uni.request({
    url: `https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=${ACCESS_KEY}&client_secret=${ACCESS_SECRET}`,
    method: "POST",
    success: (res) => {
      uni.setStorage({
        data: res.data.refresh_token,
        key: "baidu-voice-token",
      });
    },
  });
}

// 语音识别
export function soundReco(data) {
  let token = uni.getStorageSync("baidu-voice-token");
  if (!token) {
    getBaiduVoiceToken();
  }
  return new Promise((resolve, regest) => {
    uni.request({
      url: `https://vop.baidu.com/server_api?dev_pid=1537&cuid=43362463&token=${token}`,
      method: "POST",
      data: data,
      header: { "Content-Type": "audio/pcm;rate=16000" },
      success: (res) => {
        if (res.data.err_msg === "success.") {
          resolve(res.data.result[0]);
        } else {
          regest();
        }
      },
      fail: ()=>{
        regest();
      } 
    });
  });
}
